import java.util.GregorianCalendar;
import java.util.LinkedList;

public class WriteThread implements Runnable {
	private LinkedList<Measurement> queue;
	private Database db;
	private static final int QUEUE_SIZE = 10;	
	private static GregorianCalendar fakedate = new GregorianCalendar(2000,1,1,1,1,1);
	
	public WriteThread(Database db) {
		this.db = db;
		queue = new LinkedList<Measurement>();	
	}

	
	
	public synchronized void add(Measurement measurement) {
		queue.addLast(measurement);
		//System.out.println("Measurement added to queue");
		notify();
	}
	
	public synchronized void waitForMeasurements() {
		
		while (queue.size() < QUEUE_SIZE) {
			try {
				//System.out.println("Waiting for measurements...");
				
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		StringBuffer query = new StringBuffer("INSERT INTO measurement (stn, date, time, temp, dewp, stp, slp, visib, wdsp, prcp, sndp, frshtt, cldc, wnddir)" +
				 "VALUES ");
		for(Measurement m : queue) {
			
			String date = m.getDate();
			String time = m.getTime();
			//date = ""+ fakedate.getTime().getHours() +"-"+ fakedate.MONTH +"-"+ fakedate.DATE;
			//time = ""+ fakedate.HOUR + ":" + fakedate.MINUTE + ":" + fakedate.SECOND; 

			query.append("(" + m.getStn() + ",'"+ date + "','"+  time + "','" +  m.getTemp() + "','" 
						+  m.getDewp() + "','" +  m.getStp() + "','" +  m.getSlp()+ "','" +  m.getVisib()+ "','" +  m.getWdsp()+ "','"
				 	+  m.getPrcp()+ "','" +  m.getSndp()+ "'," +  m.getFrshtt()+ ",'" +  m.getCldc() + "'," +  m.getWnddir() + ") ");
			if(queue.getLast() == m) {
				query.append(";");
			}
			else {
				query.append(",");
			}
		}
		queue.clear();
		System.out.println(query.toString());
		db.insert(query.toString());

	    System.out.println("Measurement writen to database");
	}
	
	@Override
	public void run() {
		while(true) {
			waitForMeasurements();
		}
	}

}
